package com.wenhuitec.android.tang.ui.view;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dhkj.web.bean.OrderProductModel;
import com.dhkj.web.utils.MyObserverRes;
import com.dhkj.web.utils.RequestUtils;
import com.wenhuitec.android.tang.R;
import com.wenhuitec.android.tang.entity.Foods;
import com.wenhuitec.android.tang.entity.Orders;
import com.wenhuitec.android.tang.ui.adapter.FoodsAdapter;
import com.wenhuitec.android.tang.ui.dialog.TuihuoDialog;
import com.wenhuitec.android.tang.util.BytesUtil;
import com.wenhuitec.android.tang.util.UsbPrinter;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class OrderView extends LinearLayout {

    private TextView orderTv;
    private TextView amountCountTv;
    private TextView amountPriceTv;
    private TextView orderTimeTv;
    private TextView cardnoTv;
    private RecyclerView recyclerView;
    private UsbPrinter usbPrinter;
    FoodsAdapter foodsAdapter;
    private Button printBut;

    private TextView nameTv;
    private OrderProductModel orderProductModel;
    private Button tuihuoBut;
    private boolean isTuikuan = false;
    List<Foods> tuikuiFoods = new ArrayList<>();
    private OrderReturn orderReturn;

    public void setOrderReturn(OrderReturn orderReturn) {
        this.orderReturn = orderReturn;
    }

    public OrderView(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.view_orders, this, true);
        orderTv = findViewById(R.id.orderTv);
        amountCountTv = findViewById(R.id.productACountTv);
        amountPriceTv = findViewById(R.id.productAPriceTv);
        recyclerView = findViewById(R.id.foodsRv);
        orderTimeTv = findViewById(R.id.orderTimeTv);
        cardnoTv = findViewById(R.id.cardnoTv);
        foodsAdapter = new FoodsAdapter(context, new ArrayList<>());
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(foodsAdapter);
        tuihuoBut = findViewById(R.id.tuihuoBut);
        usbPrinter = UsbPrinter.getInstance(context);
        printBut = findViewById(R.id.printBut);
        nameTv = findViewById(R.id.nameTv);
        printBut.setOnClickListener(view -> {
            byte[] printByte = BytesUtil.printProduct(orderProductModel);
            if (printByte != null) {
                try {
                    usbPrinter.write(printByte);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        tuihuoBut.setOnClickListener(view -> {
            if (isTuikuan) {
                SharedPreferences sharedPreferences =
                        context.getSharedPreferences("systemI", Context.MODE_PRIVATE); //私有数据
                String user = sharedPreferences.getString("user", "");
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("tuikuiFoods", tuikuiFoods);
                jsonObject.put("posnum", user);
                //发起退款
                RequestUtils.tuikuoOrder(context, new MyObserverRes<String>(context) {
                    @Override
                    public void onSuccess(String result) {
                        if (orderReturn != null) {
                            orderReturn.onReturn();
                        }
                    }

                    @Override
                    public void onFailure(Throwable e, String errorMsg) {

                    }
                }, jsonObject.toJSONString());

                shows(this.orders);
                return;
            }
            tuikuiFoods = new ArrayList<>();
            isTuikuan = true;
            printBut.setVisibility(GONE);
            tuihuoBut.setText("确定");
        });
        foodsAdapter.setOnClick(foods -> {
            if (!isTuikuan) {
                return;
            }


            TuihuoDialog tuihuoDialog = new TuihuoDialog(context);
            BigDecimal productStock = foodsAdapter.getFoodsStock(foods.getDeviceId());
            tuihuoDialog.setMessage(foods.getName() + "当前可退【" + productStock.toPlainString() + "】");
            tuihuoDialog.setStock(foods.getNumber());
            tuihuoDialog.show();
            tuihuoDialog.setYesOnClickListener("确定", number -> {
                if (new BigDecimal(number).compareTo(productStock) > 0) {
                    Toast.makeText(context, "退货超出限制", Toast.LENGTH_LONG).show();
                    return;
                }
                List<OrderProductModel.Product> productList = orders.getOrderProductModel().getProductList();
                OrderProductModel.Product product = new OrderProductModel.Product();
                product.setPrice(foods.getProductPrice());
                product.setDeviceId(foods.getDeviceId());
                product.setDeviceName(foods.getName());
                product.setNumber("-" + number);
                productList.add(product);
                Foods foodsTemp = new Foods();
                foodsTemp.setDeviceId(foods.getDeviceId());
                foodsTemp.setName(foods.getDeviceId());
                foodsTemp.setNumber("-" + number);
                foodsTemp.setProductPrice(foods.getPrice());
                foodsTemp.setDh(foods.getDh());
                tuikuiFoods.add(foodsTemp);
                initShow();
            });
        });
    }

    private Orders orders;

    public void shows(Orders orders) {
        isTuikuan = false;
        printBut.setVisibility(VISIBLE);
        tuihuoBut.setText("退货");
        this.orders = orders;
        initShow();
    }


    public void initShow() {
        orderTv.setText("单号：" + orders.getOrders());
        cardnoTv.setText("CardNo:" + orders.getCardno());

        orderTimeTv.setText(orders.getOrdersTime());
        List<Foods> foodsList = new ArrayList<>();
        BigDecimal price = new BigDecimal(0);
        BigDecimal count = new BigDecimal(0);
        orderProductModel = orders.getOrderProductModel();
        String ordersStr = orders.getOrders();
        for (OrderProductModel.Product goo : orders.getOrderProductModel().getProductList()) {
            Foods foods = new Foods();
            foods.setDeviceId(goo.getDeviceId());
            foods.setName(goo.getDeviceName());
            foods.setNumber(new BigDecimal(goo.getNumber())
                    .stripTrailingZeros().toPlainString());
            foods.setPrice(new BigDecimal(goo.getNumber())
                    .multiply(new BigDecimal(goo.getPrice())).stripTrailingZeros().setScale(2).toPlainString());
            foods.setProductPrice(goo.getPrice());
            foods.setDh(ordersStr);
            foodsList.add(foods);
            price = price.add(new BigDecimal(foods.getPrice()));
            count = count.add(new BigDecimal(foods.getNumber()));
        }
        amountCountTv.setText("X" + count.stripTrailingZeros().toPlainString());
        amountPriceTv.setText("￥" + price.stripTrailingZeros().toPlainString());

        foodsAdapter.setFoodsList(foodsList);
    }

    public static interface OrderReturn {
        void onReturn();
    }
}
